package com.youfang.sixthmedia.ui.weibo.sina;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

public class SinaWeiboOAuth2Activity extends Activity {
	public static String URL_OAUTH2_ACCESS_AUTHORIZE = "https://api.weibo.com/oauth2/authorize";

	private String mUrl;
	private ProgressDialog loading;
	private WebView mWebView;
	private RelativeLayout mContent;

	private final static String TAG = "Weibo-WebView";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		loading = new ProgressDialog(this);
		loading.requestWindowFeature(Window.FEATURE_NO_TITLE);
		loading.setMessage("Loading...");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mContent = new RelativeLayout(this);

		// get the request uri
		WeiboParameters parameters = new WeiboParameters();
		parameters.add("client_id", Utility.CONSUMER_KEY);
		parameters.add("response_type", "token");
		parameters.add("redirect_uri", Utility.REDIRECT_URI);
		parameters.add("display", "mobile");
		this.mUrl = URL_OAUTH2_ACCESS_AUTHORIZE + "?"
				+ Utility.encodeUrl(parameters);

		setUpWebView();

		addContentView(mContent, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
	}

	private void setUpWebView() {
		// webViewContainer.setOrientation(LinearLayout.VERTICAL);

		// webViewContainer.addView(title, new
		// LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
		// getContext().getResources().getDimensionPixelSize(R.dimen.dialog_title_height)));

		mWebView = new WebView(this);
		mWebView.setVerticalScrollBarEnabled(false);
		mWebView.setHorizontalScrollBarEnabled(false);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.setWebViewClient(new WeiboWebViewClient());
		mWebView.loadUrl(mUrl);
		mWebView.setLayoutParams(new FrameLayout.LayoutParams(
				ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.FILL_PARENT));
		mWebView.setVisibility(View.INVISIBLE);
		mContent.addView(mWebView);
	}

	private class WeiboWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Log.d(TAG, "Redirect URL: " + url);
			// 待后台增加对默认重定向地址的支持后修改下面的逻辑
			if (url.startsWith(Utility.REDIRECT_URI)) {
				handleRedirectUrl(view, url);
				return true;
			}
			// launch non-dialog URLs in a full browser
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
			return true;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);

			finish();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.d(TAG, "onPageStarted URL: " + url);
			// google issue. shouldOverrideUrlLoading not executed
			if (url.startsWith(Utility.REDIRECT_URI)) {
				handleRedirectUrl(view, url);
				view.stopLoading();
				return;
			}
			super.onPageStarted(view, url, favicon);
			loading.show();
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			Log.d(TAG, "onPageFinished URL: " + url);
			super.onPageFinished(view, url);
			loading.dismiss();
			mContent.setBackgroundColor(Color.TRANSPARENT);
			// mBtnClose.setVisibility(View.VISIBLE);
			mWebView.setVisibility(View.VISIBLE);
		}

		public void onReceivedSslError(WebView view, SslErrorHandler handler,
				SslError error) {
			handler.proceed();
		}

	}

	private void handleRedirectUrl(WebView view, String url) {
		Bundle values = Utility.parseUrl(url);

		String error = values.getString("error");
		String error_code = values.getString("error_code");
		CookieSyncManager.createInstance(SinaWeiboOAuth2Activity.this);
		if (error == null && error_code == null) {
			CookieSyncManager.getInstance().sync();
			Intent retIntent = new Intent();
			retIntent.putExtras(values);

			this.setResult(Activity.RESULT_OK, retIntent);
		}

		finish();
	}

}
